// pages/moni/moni.js
var r = "",
    a = require("../../utils/underscore-min.js"),
    question = require('../../utils/question.js'),
    s = 1,
    d = [],
    n = "",
    i = [];
var app = getApp();    
var util = require('../../utils/util.js');
let md5 = require('../../utils/md5.js').md5;

Page({
  data: {
    circular: true,
    currIndex: 0, //数据索引
    swiperIndex: 0, //swiper索引
    swiperItems: [],
    selectedresults: {},
    StorageAll:{},
    orderPX:{},
    redNum: 0,
    greenNum: 0,
    allNum: 0,
    iconInd: !1,
    iconIndtwo: !1,
    indexInd: 0,
    current: 0,
    textTab: "答题模式",
    selectInd: !0,
    testMode: !1,
    everyDay_all: 0,
    xiejie: !0,
    interval: 300,
    moreArr: {
      A: !1,
      B: !1,
      C: !1,
      D: !1
    },
    everyDay_error: 0,
    everyDay_all: 0,
    mode: "1",
    idarr: [],
    questions: [],
    recmend: !1,
    cateName:"",
    mode:'',
    starshow: !1,
  },

  onLoad: function (options) {
    console.log(options);
    this.get(options.exam);
    let ordernum = this.generate();
    this.setData({
      ordernum,
      times: "45:00",
    });
  },
  generate: function(){
    return util.formatTime(new Date());
  },
  onReady: function () {

  },

  onShow: function () {

  },
  
  starcollect:function(){
    this.setData({
      starshow:!this.data.starshow
    });
    console.log(this.data.current);
    console.log(this.data.questions);
    this.addFav(this.data.questions[this.data.current]);

  },
  addFav: function(q){
    let that = this;

    const db = wx.cloud.database()
    db.collection('favor').add({
      data: {
        qid: q['_id'],
        question: q
      },
      success: res => {
        console.log('[数据库] [新增记录] 成功，记录 _id: ', res._id)
        // 在返回结果中会包含新创建的记录的 _id
        wx.showToast({
          title: '新增记录成功',
        })
        
        
      },
      fail: err => {
        wx.showToast({
          icon: 'none',
          title: '新增记录失败'
        })
        console.error('[数据库] [新增记录] 失败：', err)
      }
    })
  },

  init_play:function(mode){
    let category = wx.getStorageSync('category');
    let s = category._id;
    let that = this;
    this.setData({
      mode: mode
    });
    wx.setNavigationBarTitle({
      title: '答题助手',
    });
    that.onQuery();
  },
  onQuery:function(){
    let that = this;

    const db = wx.cloud.database()
    db.collection('question').get().then(res => {
      console.log('[数据库] [查询记录] 成功: ', res)
      let items = res.data;
      items.map((it)=>{
        it.options = JSON.parse(it.options);
      })
      that.setData({
        questions:res.data
      });
    })
  },
  getthree:function() {
    var t = this;
    console.log(n + "ind" + s);
    wx.getStorage({
      key: n + "ind" + s,
      success:function(a) {
        var e = {
          currentTarget: {
            dataset: {
              index: a.data
            }
          }
        }
        t.jumpToQuestion(e);
      },
      fail: function () {
        var a = {
          currentTarget: {
            dataset: {
              index: 0
            }
          }
        };
        t.jumpToQuestion(a);
      }
    }), wx.getStorage({
      key: n + "" + s,
      success: function (a) {
        if (a.data) {
          var e = t.data.orderPX;
          e[t.data.idarr[a.data]] = 'blue', t.setData({
            orderPX: e,
            recmend: !0
          }), t.questionStatus(), setTimeout(function () {
            t.setData({
              recmend: !1
            });
          }, 2e3);
        }
      }
    })
  },
  jumpToQuestion:function(t) {
    var a = this,
      e = a.data.orderPX;
    for (var r in e) "blue" == e[r] && (e[r] = "");
    this.setData({
      orderPX: e,
      iconInd: !1,
      iconIndtwo: !1,
      videoctrl: !0
    });
    var n = t.currentTarget.dataset.color;
    console.log(n)
    if ("red" != n && "green" != n) {
      var i = a.data.orderPX;
      i[t.currentTarget.dataset.id] = "blue", a.setData({
        orderPX: i
      })
    }
    console.log(a.data.orderPX)
    //a.getListOrder()
    var o = t.currentTarget.dataset.index;
    a.data.indexInd = o;
    var u = [];
    console.log(d[o])
    1 == this.data.current ? (a.data.indexInd <= 0 ? u.push(d[d.length - 1]) : u.push(d[a.data.indexInd - 1]),
      u.push(d[a.data.indexInd]), a.data.indexInd >= d.length - 1 ? u.push(d[0]) : u.push(d[d.length - 1])) : 0 == this.data.current ? (u.push(d[a.data.indexInd]),
        a.data.indexInd == d.length - 1 ? (u.push(d[0]), u.push(d[1])) : a.data.indexInd == d.length - 2 ? (u.push(d[a.data.indexInd + 1]),
          u.push(d[0])) : (u.push(d[a.data.indexInd + 1]), u.push(d[a.data.indexInd + 2]))) : (0 == a.data.indexInd ? (u.push(d[d.length - 2]),
            u.push(d[d.length - 1])) : 1 == a.data.indexInd ? (u.push(d[d.length - 1]), u.push(d[0])) : (u.push(d[a.data.indexInd - 2]),
              u.push(d[a.data.indexInd - 1])), u.push(d[a.data.indexInd])), this.setData({
                questions: u,
                indexInd: o
              })
    getApp().saveInfo("starids",s,d[o].question_id.toString()),setTimeout(function() {
      a.setData({
        starshow:getApp().info
      })
    },500)
    console.log(u)
  },
  questionStatus: function () {
    var t = this;
    wx.getStorage({
      key: n + "list" + s,
      success: function (a) {
        t.setData({
          orderPX: a.data,
          allNum: a.data.all
        });
      }
    });
  },
  touchstart: function (t) { },
  bindtouchmove: function (t) { },
  bindtouchend: function (t) { },
  selectAnswer: function (t) {
    console.log('selectAnswer');
    console.log(app.globalData.questions);
    console.log(t);
    console.log(t.currentTarget.dataset);
    let item = JSON.parse(t.currentTarget.dataset.value);
    if(item.selected){
      return;
    }
    let code = t.currentTarget.dataset.code;
    let answer = t.currentTarget.dataset.answer;
    let options = item.options;

    let greenNum = this.data.greenNum;
    let redNum = this.data.redNum;
    item.right = 0;
    options.map(o => {
      o.selected = false;
      if(o.code == code){
        o.selected = true;
      }
      if((o.code == code)&&(o.code == answer)){
        o.val = 1;
        greenNum++;
        item.right = 1;
      }
      if((o.code == code)&&(o.code != answer)){
        o.val = 0;
        redNum++;
      }
    })
    console.log(item);
    item.options = options;
    item.selected = true;

    app.globalData.questions[this.data.currIndex] = item;


    let newSwiperItems = [];
    this.data.swiperItems.map((ele) => {
      let index = ele.index;
      console.log('更新：'+index);
      if(index == item.index){
        ele = item;
      }
      newSwiperItems.push(ele);
    })

    this.setData({
      greenNum: greenNum,
      redNum: redNum,
      swiperItems: newSwiperItems
    })
    if(this.data.currIndex == app.globalData.questions.length - 1){
      console.log(this.data.currIndex,app.globalData.questions.length)
      this.result();
    }else{
      this.autoPlay();
    }
  },
  selectAnswerMore:function(t){
    var a = this;
    if ("背题模式" != a.data.textTab && "1" != a.data.questions[a.data.current].order.subup) {
      var e = a.data.StorageAll,
        r = a.data.moreArr;
      r[t.currentTarget.dataset.ind] ? r[t.currentTarget.dataset.ind] = !1 : r[t.currentTarget.dataset.ind] = !0,
        e[t.currentTarget.dataset.id] = {
          subup: 0,
          down: r
        }, a.setData({
          moreArr: r
        }), wx.setStorage({
          key: n + "" + s,
          data: e,
        }), wx.getStorage({
          key: n + "" + s,
          success: function (t) {
            a.setData({
              StorageAll: t.data
            })
          },
        });
      var d = a.data.questions;
      d[a.data.current].textTab = a.data.textTab, d[a.data.current].order = e[t.currentTarget.dataset.id],
        a.setData({
          questions: d
        })
    }
  },
  moreSelectSub: function (t) {
    console.log(this.data.moreArr)
    function a() {
      if (o = e.data.idarr[i], i < e.data.idarr.length - 1) {
        if ("green" != e.data.orderPX[o] && "red" != e.data.orderPX[o]) {
          wx.setStorage({
            key: n + "ind" + s,
            data: i
          });
          var t = e.data.orderPX;
          for (var r in t) "blue" == t[r] && (t[r] = "");
          return t[o] = "blue", e.setData({
            orderPX: t
          }), void console.log(e.data.orderPX);
        }
        i++ , a();
      } else wx.setStorage({
        key: n + "ind" + s,
        data: e.data.idarr.length - 1
      });
    }
    var e = this,
      i = e.data.indexInd + 1,
      o = e.data.idarr[i];
    a();
    var u = e.data.StorageAll,
      l = e.data.moreArr;
    u[t.currentTarget.dataset.id] = {
      subup: 1,
      down: l
    }, e.setData({
      StorageAll: u
    }), wx.setStorage({
      key: n + "" + s,
      data: u,
    });
    var c = e.data.questions,
      g = d;
    g[e.data.indexInd].textTab = e.data.textTab, g[e.data.indexInd].order = {
      subup: 1,
      down: l
    }, c[e.data.current].textTab = e.data.textTab, c[e.data.current].order = {
      subup: 1,
      down: l
    }, d = g, e.setData({
      questions: c
    });
    var h = 0;
    var downAnswer = ""
    for (var v in e.data.moreArr) {
      if (e.data.moreArr[v]) {
        h++;
        downAnswer += v
      }

    }
    console.log(downAnswer)
    var f = e.data.allNum;
    console.log(f)
    if (f++ , h == t.currentTarget.dataset.answer.length && downAnswer == t.currentTarget.dataset.answer) {
      (x = e.data.orderPX)[t.currentTarget.dataset.id] = "green", x.all = f, wx.setStorage({
        key: n + "list" + s,
        data: x
      });
      var p = e.data.greenNum;
      p++ , e.setData({
        greenNum: p
      }), e.questionStatus(), e.autoPlay();
      w = e.data.everyDay_all;
      w++ , e.setData({
        everyDay_all: w
      });
    } else {
      getApp().setIdsStroage("errorids", s, "1", c[e.data.current].question_id.toString());
      var x = e.data.orderPX;
      console.log(x)
      x[t.currentTarget.dataset.id] = "red", x.all = f, wx.setStorage({
        key: n + "list" + s,
        data: x,
      })
      var y = e.data.redNum;
      y++ , e.setData({
        redNum: y
      }), e.questionStatus();
      var D = e.data.everyDay_error,
        w = e.data.everyDay_all;
      r += "," + t.currentTarget.dataset.id, D++ , w++ , e.setData({
        everyDay_error: D,
        everyDay_all: w
      });
    }
    e.setData({
      moreArr: {
        A: !1,
        B: !1,
        C: !1,
        D: !1
      }
    });
  },

  autoPlay: function () {
    console.log('autoplay');
    this.setData({
      autoplay: true
    });

  },

  pageChange: function (e) {
    console.log('pageChange');
    console.log(e.detail);

    console.log('[滑动]');
    console.log(this.data.currIndex);
    console.log(app.globalData.questions.length);
   

    //更新swiper索引
    let newCurrent = e.detail.current;
    let oldCurrent = this.data.swiperIndex;
    this.data.swiperIndex = newCurrent;

    //更新数据索引
    if (newCurrent === oldCurrent + 1 || oldCurrent + 1 === this.data.swiperItems.length + newCurrent) { //正向
      console.log('正向')
      this.data.currIndex++;
    } else { //逆向
      console.log('逆向')
      this.data.currIndex--;
    }

    //数据索引边界处理
    if (this.data.currIndex > app.globalData.questions.length - 1) {
      this.data.currIndex = 0;
    } else if (this.data.currIndex < 0) {
      this.data.currIndex = app.globalData.questions.length - 1;
    }
    console.log('取模');
    console.log('this.data.currIndex');
    console.log(this.data.currIndex);
    console.log((this.data.currIndex)%3);

    let swiperItems = this.data.swiperItems;
    // let circular;
    // if (this.data.currIndex == app.globalData.questions.length - 1) {
    //   circular = false;
    //   let mo = (this.data.currIndex)%3;
      
    //   console.log(swiperItems);
    //   if(mo == 0){
    //     swiperItems.pop();
    //     swiperItems.pop();
    //   }
    //   if(mo == 1){
    //     swiperItems.pop();
    //   }
    //   if(mo == 2){

    //   }
    //   this.setData({
        
    //   },()=>{
    //     console.log('已是最后一题')
    //     console.log(swiperItems)
    //   })
    // }
    
    //确定三个item的数据值
    let curr = app.globalData.questions[this.data.currIndex]
    let next = this.data.currIndex === app.globalData.questions.length - 1 ? 0 : app.globalData.questions[this.data.currIndex + 1];
    let pre = this.data.currIndex === 0 ? app.globalData.questions[app.globalData.questions.length - 1] : app.globalData.questions[this.data.currIndex - 1];

    
    //当前item不用处理，其他两个item更新显示；
    if (this.data.swiperIndex === 0) {
      swiperItems[1] = next;
      swiperItems[2] = pre;
    } else if (this.data.swiperIndex === 1) {
      swiperItems[0] = pre;
      this.data.swiperItems[2] = next;
    } else if (this.data.swiperIndex === 2) {
      swiperItems[0] = next;
      swiperItems[1] = pre;
    }
    
    
    this.setData({
      currIndex: this.data.currIndex,
      swiperItems: swiperItems,
      circular: true,
      me:[],
      starshow: false,
      autoplay: false
    },()=>{
      console.log(this.data.swiperItems);
    })
  },

  _updown: function () {
    var t = this;
    this.setData({
      iconInd: !this.data.iconInd,
      iconIndtwo: !this.data.iconIndtwo
    }), setTimeout(function () {
      i.length < 2 || t.setData({
        scrolltop: i[i.length - 2]
      });
    }, 0);
    console.log(this.data.iconInd)
  },
  changeTab: function (t) {
    var that = this
    var questions = that.data.questions;
    that.setData({
      questions: questions,
      textTab: t.currentTarget.dataset.texttab,
      selectInd: "答题模式" == t.currentTarget.dataset.texttab,
      testMode: "答题模式" == t.currentTarget.dataset.texttab
    })
  },
  del_data:function(){
    var t = this;
    wx.showModal({
      content: '确定要清空吗？',
      success:function(a){
        if(a.confirm){
          var e = n + "ind" + s,
            r = n + "list" + s,
            i = n + "" + s;
          wx.removeStorageSync(i), wx.removeStorageSync(r), wx.removeStorageSync(e);
          var o = {
            mode: t.data.mode
          };
          d = [], t.setData({
            iconInd: !1,
            StorageAll: {},
            everyDay_error: 0,
            greenNum: 0,
            redNum: 0,
            orderPX: {}
          }), t.init_play(o);
        }
      }
    })
  },
  onUnload: function() {


  },
  get: function(examid) {
    let that = this;
    // 调用云函数
    wx.cloud.callFunction({
      name: 'get',
      data: {
        examid: examid
      },
      success: res => {
        console.log('[云函数] [get]: ', res)
        let items = res.result.data;
        let newItems = items.filter(item => item.examid==examid);
        console.log(items);
        console.log(newItems);
        let questions = [];
        newItems.forEach((item, idx) =>{
          item.index = idx;
          item.right = -1;
          let options = item.options;
          let formatedOptions = [];
          options.forEach((option)=>{
            option.selected = false;
            option.val = parseInt(option.value);
            formatedOptions.push(option)
          })
          item.options = formatedOptions;
          item.selected = false;
          questions.push(item);
        })
        console.log(questions);
        app.globalData.questions = questions;
        let swiperItems = questions.slice(0,3);
        console.log(swiperItems);
        this.setData({
          // questions
          nums: questions.length,
          swiperItems,
        },()=>{
          console.log('001');
          console.log(this.data);
        })
      },
      fail: err => {
        console.error('[云函数] [login] 调用失败', err)
        wx.navigateTo({
          url: '../deployFunctions/deployFunctions',
        })
      }
    })
  }

})